// 在文件顶部的头文件后添加JNI相关的头文件
#include <jni.h>
#include <string>
#include <thread>
#include <atomic>
#include <random>
#include <android/log.h>
#include <android/trace.h>

#define TAG "SensorServiceNative"
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, TAG, __VA_ARGS__)
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, TAG, __VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__)
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN, TAG, __VA_ARGS__)

// 在需要的地方添加Trace宏定义
#define TRACE_BEGIN(name) ATrace_beginSection(name)
#define TRACE_END() ATrace_endSection()

// 全局变量
static JavaVM* gJavaVM = nullptr;
static jobject gServiceObj = nullptr;
static std::atomic<bool> gIsRunning(false);
static std::thread gSensorThread;
static std::mutex gThreadMutex;

// 函数前向声明
static void notifySensorData(JNIEnv* env, float x, float y, float z);
static void notifySensorStatus(JNIEnv* env, bool isRunning);
static void sensorThreadFunc();
static JNIEnv* getJNIEnv();
static void detachThread();
// 添加缺少的函数前向声明
// 修改函数前向声明
// 原代码：JNIEXPORT void JNICALL Java_com_example_suhui_test_service_SensorService_nativeStopSensor(JNIEnv* env, jobject thiz);
JNIEXPORT void JNICALL Java_com_example_suhui_test_service_SensorService_nativeStopSensor(JNIEnv* env, jobject thiz);

// 注意：看起来包名中的下划线可能需要特殊处理
// 让我们修改所有JNI函数定义，确保它们与Java端期望的命名完全匹配：

// 修改 nativeInit 函数定义
// 原代码：Java_com_example_suhui_test_service_SensorService_nativeInit
JNIEXPORT void JNICALL
Java_com_example_suhui_test_service_SensorService_nativeInit(JNIEnv* env, jobject thiz) {
    TRACE_BEGIN("SensorService_native_nativeInit");
    LOGD("Native initialized");
    
    // 保存全局引用
    if (env->GetJavaVM(&gJavaVM) != JNI_OK) {
        LOGE("Failed to get JavaVM");
    } else {
        LOGD("JavaVM obtained successfully");
    }
    
    if (thiz) {
        gServiceObj = env->NewGlobalRef(thiz);
        if (gServiceObj) {
            LOGD("Service global reference created successfully");
        } else {
            LOGE("Failed to create service global reference");
        }
    } else {
        LOGE("Service object is null");
    }
    
    // 初始化运行状态
    gIsRunning = false;
    
    LOGI("Native initialization completed");
    TRACE_END();
}

JNIEXPORT void JNICALL
Java_com_example_suhui_test_service_SensorService_nativeRelease(JNIEnv* env, jobject thiz) {
    TRACE_BEGIN("SensorService_native_nativeRelease");
    LOGD("Native releasing resources");
    
    // 停止传感器
    Java_com_example_suhui_test_service_SensorService_nativeStopSensor(env, thiz);
    
    // 等待线程结束（如果正在运行）
    { // 锁定线程互斥量
        std::lock_guard<std::mutex> lock(gThreadMutex);
        if (gSensorThread.joinable()) {
            LOGD("Waiting for sensor thread to join");
            gSensorThread.join();
            LOGD("Sensor thread joined successfully");
        }
    }
    
    // 释放全局引用
    if (gServiceObj && env) {
        env->DeleteGlobalRef(gServiceObj);
        gServiceObj = nullptr;
        LOGD("Service global reference deleted");
    }
    
    gJavaVM = nullptr;
    LOGI("Native resources released completely");
    
    TRACE_END();
}

JNIEXPORT void JNICALL
Java_com_example_suhui_test_service_SensorService_nativeStartSensor(JNIEnv* env, jobject thiz) {
    TRACE_BEGIN("SensorService_native_nativeStartSensor");
    LOGD("Starting sensor");
    
    if (!gIsRunning) {
        { // 锁定线程互斥量
            std::lock_guard<std::mutex> lock(gThreadMutex);
            if (!gIsRunning) { // 双重检查锁定模式
                gIsRunning = true;
                try {
                    // 创建新的传感器线程
                    gSensorThread = std::thread(sensorThreadFunc);
                    // 不分离线程，以便在释放时可以join
                    LOGI("Sensor thread created successfully");
                } catch (const std::system_error& e) {
                    LOGE("Failed to create sensor thread: %s", e.what());
                    gIsRunning = false;
                }
            }
        }
    } else {
        LOGW("Sensor is already running");
    }
    
    TRACE_END();
}

JNIEXPORT void JNICALL
Java_com_example_suhui_test_service_SensorService_nativeStopSensor(JNIEnv* env, jobject thiz) {
    TRACE_BEGIN("SensorService_native_nativeStopSensor");
    LOGD("Stopping sensor");
    
    if (gIsRunning) {
        gIsRunning = false;
        // 不需要立即等待线程结束，让它自然退出
        LOGI("Sensor stopped, waiting for thread to exit gracefully");
    } else {
        LOGW("Sensor is not running");
    }
    
    TRACE_END();
}

JNIEXPORT jboolean JNICALL
Java_com_example_suhui_test_service_SensorService_nativeIsSensorRunning(JNIEnv* env, jobject thiz) {
    TRACE_BEGIN("SensorService_native_nativeIsSensorRunning");
    jboolean result = gIsRunning.load() ? JNI_TRUE : JNI_FALSE;
    LOGD("Sensor running status: %s", (result ? "true" : "false"));
    TRACE_END();
    return result;
}

// 通知Java层传感器数据
static void notifySensorData(JNIEnv* env, float x, float y, float z) {
    TRACE_BEGIN("SensorService_native_notifySensorData");
    
    if (!gServiceObj || !env) {
        LOGE("Invalid parameters for notifySensorData");
        TRACE_END();
        return;
    }
    
    // 记录详细日志
    LOGD("Notifying sensor data: x=%.4f, y=%.4f, z=%.4f", x, y, z);
    
    jclass cls = env->GetObjectClass(gServiceObj);
    if (!cls) {
        LOGE("Failed to get service class");
        TRACE_END();
        return;
    }
    
    jmethodID methodId = env->GetMethodID(cls, "notifySensorData", "(FFF)V");
    if (!methodId) {
        LOGE("Failed to get notifySensorData method");
        env->DeleteLocalRef(cls);
        TRACE_END();
        return;
    }
    
    // 调用Java方法
    env->CallVoidMethod(gServiceObj, methodId, x, y, z);
    
    // 检查是否有异常发生
    if (env->ExceptionCheck()) {
        LOGE("Exception occurred when calling notifySensorData");
        env->ExceptionClear();
    }
    
    // 释放本地引用
    env->DeleteLocalRef(cls);
    TRACE_END();
}

// 通知Java层传感器状态
static void notifySensorStatus(JNIEnv* env, bool isRunning) {
    TRACE_BEGIN("SensorService_native_notifySensorStatus");
    
    if (!gServiceObj || !env) {
        LOGE("Invalid parameters for notifySensorStatus");
        TRACE_END();
        return;
    }
    
    // 记录详细日志
    LOGD("Notifying sensor status: %s", (isRunning ? "running" : "stopped"));
    
    jclass cls = env->GetObjectClass(gServiceObj);
    if (!cls) {
        LOGE("Failed to get service class");
        TRACE_END();
        return;
    }
    
    jmethodID methodId = env->GetMethodID(cls, "notifySensorStatus", "(Z)V");
    if (!methodId) {
        LOGE("Failed to get notifySensorStatus method");
        env->DeleteLocalRef(cls);
        TRACE_END();
        return;
    }
    
    // 调用Java方法
    env->CallVoidMethod(gServiceObj, methodId, isRunning);
    
    // 检查是否有异常发生
    if (env->ExceptionCheck()) {
        LOGE("Exception occurred when calling notifySensorStatus");
        env->ExceptionClear();
    }
    
    // 释放本地引用
    env->DeleteLocalRef(cls);
    TRACE_END();
}

// 传感器线程函数实现
static void sensorThreadFunc() {
    TRACE_BEGIN("SensorService_native_sensorThreadFunc");
    LOGD("Sensor thread started");
    
    // 获取JNI环境
    JNIEnv* env = getJNIEnv();
    if (!env) {
        LOGE("Failed to get JNIEnv in sensor thread");
        TRACE_END();
        return;
    }
    
    // 通知传感器状态为运行中
    notifySensorStatus(env, true);
    
    // 创建随机数生成器
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_real_distribution<float> dist(-1.0f, 1.0f);
    
    // 传感器数据生成循环
    while (gIsRunning) {
        // 生成随机传感器数据
        float x = dist(gen);
        float y = dist(gen);
        float z = dist(gen);
        
        // 通知Java层传感器数据
        notifySensorData(env, x, y, z);
        
        // 短暂休眠，模拟传感器采样频率
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }
    
    // 通知传感器状态为已停止
    notifySensorStatus(env, false);
    
    // 分离当前线程
    detachThread();
    
    LOGD("Sensor thread exited");
    TRACE_END();
}

// 获取JNI环境
static JNIEnv* getJNIEnv() {
    JNIEnv* env = nullptr;
    if (gJavaVM) {
        // 尝试获取当前线程的JNI环境
        if (gJavaVM->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
            // 如果获取失败，则附加当前线程到JVM
            if (gJavaVM->AttachCurrentThread(&env, nullptr) != JNI_OK) {
                LOGE("Failed to attach thread to JVM");
                return nullptr;
            }
        }
    } else {
        LOGE("JavaVM is null");
    }
    return env;
}

// 分离当前线程
static void detachThread() {
    if (gJavaVM) {
        gJavaVM->DetachCurrentThread();
        LOGD("Thread detached from JVM");
    }
}

// 在文件末尾添加JNI_OnLoad函数实现
// JNI_OnLoad函数会在native库加载时自动调用，用于显式注册JNI方法
jint JNI_OnLoad(JavaVM* vm, void* reserved) {
    JNIEnv* env = nullptr;
    
    // 获取JNI环境
    if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
        LOGE("Failed to get JNI environment in JNI_OnLoad");
        return JNI_ERR;
    }
    
    // 定义Java类路径
    const char* className = "com/example/suhui_test/service/SensorService";
    
    // 查找Java类
    jclass clazz = env->FindClass(className);
    if (clazz == nullptr) {
        LOGE("Failed to find class %s", className);
        return JNI_ERR;
    }
    
    // 定义要注册的本地方法映射表
    JNINativeMethod methods[] = {
        {
            "nativeInit",              // Java方法名
            "()V",                     // 方法签名
            reinterpret_cast<void*>(Java_com_example_suhui_test_service_SensorService_nativeInit) // 对应的C++函数指针
        },
        {
            "nativeRelease",
            "()V",
            reinterpret_cast<void*>(Java_com_example_suhui_test_service_SensorService_nativeRelease)
        },
        {
            "nativeStartSensor",
            "()V",
            reinterpret_cast<void*>(Java_com_example_suhui_test_service_SensorService_nativeStartSensor)
        },
        {
            "nativeStopSensor",
            "()V",
            reinterpret_cast<void*>(Java_com_example_suhui_test_service_SensorService_nativeStopSensor)
        },
        {
            "nativeIsSensorRunning",
            "()Z",
            reinterpret_cast<void*>(Java_com_example_suhui_test_service_SensorService_nativeIsSensorRunning)
        }
    };
    
    // 注册JNI方法
    int numMethods = sizeof(methods) / sizeof(methods[0]);
    if (env->RegisterNatives(clazz, methods, numMethods) < 0) {
        LOGE("Failed to register native methods for class %s", className);
        return JNI_ERR;
    }
    
    LOGI("Successfully registered %d native methods for class %s", numMethods, className);
    
    // 返回JNI版本
    return JNI_VERSION_1_6;
}